<template>
  <div class="gl_contentBox gl_heightFull">
    <div class="demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <el-col :span="4">
          <p>考生姓名</p>
          <el-input v-model="qo.StudentName" placeholder="请输入考生姓名" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="4">
          <p>证件号码</p>
          <el-input v-model="qo.IdCardNumber" placeholder="请输入证件号码" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="4">
          <p>申报级别</p>
          <el-input v-model="qo.DuanName" placeholder="请输入申报级别" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="4">
          <p>教练</p>
          <el-input v-model="qo.CoachName" placeholder="请输入教练" size="mini" clearable @change="getPageList()" />
        </el-col>
        <!-- <el-col :span="4">
          <p>会员费类型</p>
          <el-select v-model="qo.MemberFeeTypeCode" size="mini" placeholder="请选择会员费类型" filterable @change="getPageList()">
            <el-option label="全部" :value="null" />
            <el-option v-for="jtem in dict.memberFeeType" :key="jtem.code" :value="jtem.code" :label="jtem.value" />
          </el-select>
        </el-col> -->
        <el-col :span="4">
          <p>提交机构</p>
          <el-input v-model="qo.OrganizationUnitName" placeholder="请输入提交机构" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="4" class="search_btn">
          <el-button type="primary" size="mini" @click="getPageList()">筛选</el-button>
          <el-button type="warning" size="mini" @click="clickReset()">{{ $t('button.Reset') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <el-row class="gl_my_15">
      <el-button type="primary" size="mini" :disabled="isUpload" icon="el-icon-circle-plus-outline" @click="addStudent()">添加考生</el-button>
      <el-button v-if="editing" type="warning" :disabled="isUpload" size="mini" @click="cancelEdit">取消编辑</el-button>
      <el-button v-else type="primary" :disabled="isUpload" size="mini" @click="clickBatch">批量编辑</el-button>
      <el-button type="primary" size="mini" :disabled="isUpload" @click="clickConfirm">批量确认</el-button>
    </el-row>
    <el-table
      ref="multipleTable"
      v-loading="tableLoading"
      :data="tableData"
      class="gl_table_noBorder gl_mt_15"
      size="mini"
      @selection-change="selection"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" align="center" width="50" />
      <el-table-column label="姓名" align="center" width="70">
        <template slot-scope="{row}">
          <PersonalImage :imgurl="row.imagePath" imgheight="60px" />
          <!-- <img class="roodsPhoto" :src="getStaticFileUrl(row.imagePath)" alt=""> -->
        </template>
      </el-table-column>
      <el-table-column label="" min-width="100">
        <template slot-scope="{row}">
          {{ row.studentName || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="证件号" prop="idCardNumber" min-width="145" />
      <el-table-column label="联系方式" prop="phoneNumber" min-width="100" />
      <el-table-column label="当前级别" prop="levelType" :min-width="80">
        <template slot-scope="{ row }">
          <span v-if="row.levelType && row.duanType">{{ row.levelType.name + ' / ' + row.duanType.name }}</span>
          <span v-else>{{ row.levelType ? row.levelType.name : '' }} {{ row.duanType ? row.duanType.name : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申报级别" :min-width="80">
        <template slot-scope="{row}">
          <span v-for="(item, index) in row.duanExamStudentDuans" :key="item.duanId">
            {{ item.duan ? item.duan.name : '' }} {{ row.duanExamStudentDuans.length - 1 === index ? '': '/' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="教练" prop="coachName" :min-width="80" />
      <el-table-column label="提交机构" prop="organizationUnitName" :min-width="120" />
      <el-table-column width="100" label="成绩">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.score ? row.score : '' }}</span>
          <el-input v-else v-model.trim="row.inputScore" size="mini" />
        </template>
      </el-table-column>
      <el-table-column width="130" label="考官">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.duanExamOfficialName }}</span>
          <el-select v-else v-model="row.inputDuanExamOfficialId" size="mini" placeholder="请选择考官">
            <el-option v-for="item in officials" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column width="150" label="考试结果">
        <template slot-scope="{ row }">
          <span v-if="!row.isEdit">{{ row.scoreStatus ? row.scoreStatus.name : '' }}</span>
          <el-select v-else v-model="row.inputScoreStatusCode" size="mini" placeholder="请选择考试结果">
            <el-option v-for="item in dict.scoreStatus" :key="item.code" :label="item.value" :value="item.code" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('table.actions')" width="60">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" :disabled="isUpload" @click="clickEdit(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="gl_pt_15" style="text-align: right;">
      <el-pagination
        :current-page="qo.Page"
        :page-size="qo.MaxResultCount"
        :total="total"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </el-row>
    <addResult ref="addResult" />
  </div>
</template>

<script>
import { CopyData } from '@/lib';
import addResult from './addResult.vue';
import PersonalImage from '@/components/PersonalImage/index';
import { mapState, mapActions } from 'vuex';
import {
  Api_GET_ClubDuanExamStudentScoreStudentScoreListQO // 分页获取录入成绩的考生列表
} from '@/lib/form/hall/swaggerForm';
import {
  api_GET_ClubDuanExamStudentScoreDuanExamReportDuanExamId, // 获取考试的成绩单
  api_GET_ClubDuanExamStudentScoreStudentScoreList, // 分页获取录入成绩的考生列表
  api_POST_ClubDuanExamStudentScoreBatchApprovalStudentScore, // 批量审核学生的考试成绩
  api_GET_ClubDuanExamOfficial // 获取考官
} from '@/extend/api/hallswaggerApi/app';
export default {
  components: { addResult, PersonalImage },
  data() {
    return {
      duanExamId: '',
      qo: new Api_GET_ClubDuanExamStudentScoreStudentScoreListQO(),
      tableLoading: false,
      total: 0,
      tableData: [],
      editing: false,
      officials: [],
      selectData: [],
      selectObj: {},
      isUpload: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  created() {
    this.duanExamId = this.$route.query.id || '';
    this.getUploadInfo();
    this.getDict();
    this.getPageList();
  },
  methods: {
    // 若没有字典信息，外部可直接调用方法获取字典数据
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取是否已上传成绩单支付费用
    getUploadInfo() {
      api_GET_ClubDuanExamStudentScoreDuanExamReportDuanExamId(this.duanExamId).then(res => {
        this.isUpload = !!res;
        // console.log(res, '上传并支付查询');
        // console.log(this.isUpload);
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 分页获取录入成绩的考生列表
    getPageList(page) {
      const that = this;
      this.qo.Page = page || 1;
      this.qo.SkipCount = (this.qo.Page - 1) * this.qo.MaxResultCount;
      this.qo.DuanExamId = this.$route.query.id;
      this.qo.IncludeDuanExamRequestDuans = true;
      this.qo.IncludeLevelType = true;
      this.qo.IncludeDuanType = true;
      this.qo.IncludeScoreStatus = true;
      this.qo.IsApproved = true;
      this.qo.Sorting = 'creationTime DESC';
      this.tableLoading = true;
      api_GET_ClubDuanExamStudentScoreStudentScoreList(this.qo).then(res => {
        this.tableLoading = false;
        this.tableData = res.items;
        this.total = res.totalCount;
        this.tableData = this.tableData.map((item) => {
          that.$set(item, 'isEdit', false);
          that.$set(item, 'inputScore', item.score);
          that.$set(item, 'inputDuanExamOfficialId', item.duanExamOfficialId);
          that.$set(item, 'inputDuanExamOfficialName', item.DuanExamOfficialName);
          that.$set(item, 'inputScoreStatusCode', item.scoreStatusCode);
          return item;
        });
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 批量审核
    clickBatch() {
      const that = this;
      if (!this.selectData.length) {
        this.$message({ type: 'warning', showClose: true, message: `请先勾选要审核的考生` });
        return;
      }
      this.getExamOfficial();
      this.editing = true;
      this.selectObj = {}; // 选中项id
      this.selectData.map(item => {
        that.$set(that.selectObj, item.id, true);
      });
      this.tableData.map(item => {
        item.isEdit = that.selectObj[item.id] || false;
      });
    },
    // 批量确认
    clickConfirm() {
      if (!this.editing) {
        const msg = this.selectData.length > 0 ? '请先选择批量编辑并录入成绩' : '请先勾选考生，选择批量编辑并录入成绩';
        this.$message({ type: 'warning', showClose: true, message: msg });
        return;
      }
      const that = this;
      const qo = this.selectData.map(item => {
        const officialIndex = that.officials.findIndex(jtem => jtem.id === item.inputDuanExamOfficialId);
        return {
          duanExamStudentId: item.id,
          score: Number(item.inputScore),
          duanExamOfficialId: item.inputDuanExamOfficialId,
          duanExamOfficialName: that.officials[officialIndex] ? that.officials[officialIndex].name : '',
          scoreStatusCode: item.inputScoreStatusCode
        };
      });
      this.tableLoading = true;
      api_POST_ClubDuanExamStudentScoreBatchApprovalStudentScore(qo).then(res => {
        this.editing = false;
        this.tableLoading = false;
        this.$message({ type: 'success', message: '审核成功' });
        that.getPageList(that.qo.Page);
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 选中改变
    selection(val) {
      this.selectData = val;
      const that = this;
      this.selectObj = {};
      this.selectData.map(item => {
        that.$set(that.selectObj, item.id, true);
      });
      if (this.editing) {
        this.tableData.map(item => {
          item.isEdit = that.selectObj[item.id] || false;
        });
      }
    },
    // 点击编辑
    clickEdit(item) {
      this.$refs.addResult.dialogVisible = true;
      CopyData(item, this.$refs.addResult.studentVO);
      this.$refs.addResult.getExamOfficial(this.duanExamId);
    },
    // 取消编辑
    cancelEdit() {
      this.editing = false;
      this.tableData = this.tableData.map(item => {
        if (item.isEdit) {
          item.isEdit = false;
          item.inputScore = item.score;
          item.inputDuanExamOfficialId = item.duanExamOfficialId;
          item.inputDuanExamOfficialName = item.duanExamOfficialName;
          item.inputScoreStatusCode = item.scoreStatusCode;
        }
        return item;
      });
    },
    getExamOfficial() {
      api_GET_ClubDuanExamOfficial({ duanExamId: this.duanExamId }).then(res => {
        this.officials = res;
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    clickReset() {
      this.qo = new Api_GET_ClubDuanExamStudentScoreStudentScoreListQO();
      this.getPageList();
    },
    addStudent() {
      this.$router.push({ name: 'AddExaminee', query: { id: this.$route.query.id, type: 'declare' }});
    },
    // 上传图片回显
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 分页
    sizeChange(MaxResultCount) {
      this.editing = false;
      this.selectData = [];
      this.qo.MaxResultCount = MaxResultCount;
      this.getPageList();
    },
    pageIndexChange(currentPage) {
      this.editing = false;
      this.selectData = [];
      this.getPageList(currentPage);
    }
  }
};
</script>
<style lang="scss" scoped>
  .roodsPhoto{
    width: 60px;
    height: 60px;
    border-radius: 6px;
    vertical-align: middle;
  }
</style>
